package com.hengtongxing.hejiayun.homepage;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.BaseFragment;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.BannerListBean;
import com.hengtongxing.hejiayun.bean.GoodsListBean;
import com.hengtongxing.hejiayun.bean.IndexMessageBean;
import com.hengtongxing.hejiayun.bean.MenuListBean;
import com.hengtongxing.hejiayun.event.LoginEvent;
import com.hengtongxing.hejiayun.homepage.adapter.HomeGoodsListAdapter;
import com.hengtongxing.hejiayun.homepage.adapter.HomeMenuListAdapter;
import com.hengtongxing.hejiayun.homepage.model.HomePageModelImpl;
import com.hengtongxing.hejiayun.homepage.model.IHomePageModel;
import com.hengtongxing.hejiayun.life.GoodsListActivity;
import com.hengtongxing.hejiayun.mine.UserAgreementActivity;
import com.hengtongxing.hejiayun.shop.ShopGoodsDetailsActivity;
import com.hengtongxing.hejiayun.utils.DateTimeUtil;
import com.hengtongxing.hejiayun.utils.Dp2Px;
import com.hengtongxing.hejiayun.utils.GlideUtils;
import com.hengtongxing.hejiayun.widget.AppTitleBar;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.transformers.Transformer;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页
 */
public class HomePageFragment extends BaseFragment {


    @BindView(R.id.xbanner)
    XBanner xbanner;
    @BindView(R.id.ll_repairs)
    LinearLayout llRepairs;
    @BindView(R.id.ll_consult)
    LinearLayout llConsult;
    @BindView(R.id.ll_clean)
    LinearLayout llClean;
    @BindView(R.id.ll_fees)
    LinearLayout llFees;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.layout_title)
    LinearLayout layoutTitle;
    @BindView(R.id.ll_service_remind)
    LinearLayout llServiceRemind;
    @BindView(R.id.recyclerView_menu)
    RecyclerView recyclerViewMenu;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.tv_message1)
    TextView tvMessage1;
    @BindView(R.id.tv_message_time1)
    TextView tvMessageTime1;
    @BindView(R.id.tv_message2)
    TextView tvMessage2;
    @BindView(R.id.tv_message_time2)
    TextView tvMessageTime2;
    @BindView(R.id.ll_message1)
    LinearLayout llMessage1;
    @BindView(R.id.ll_message2)
    LinearLayout llMessage2;
    private HomeGoodsListAdapter listAdapter;
    private HomeMenuListAdapter menuListAdapter;
    private List<GoodsListBean.DataBean.ItemListBean> beanList;
    private List<MenuListBean.DataBean> menuBeanList;
    private IHomePageModel homePageModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);
        registerEventBus();
        initView();
        requestAdIndex();
        requestShopGoodsIndex();
        requestAppMenu();
        requestMessageData();
        return view;
    }

    @Subscribe
    public void loginEvent(LoginEvent event) {
        requestAdIndex();
        requestShopGoodsIndex();
        requestAppMenu();
        requestMessageData();
    }

    @Override
    public void onResume() {
        super.onResume();
        requestMessageData();
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestMessageData();
        }
    }

    @Override
    public void initImmersionBar() {
        //黑
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    public void initView() {
        homePageModel = new HomePageModelImpl();
        int height = (int) Dp2Px.dp2Px(126);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {   //设置标题的背景颜色
                    layoutTitle.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
                    titleBar.setTitle("");
                } else if (scrollY > 0 && scrollY <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) scrollY / height;
                    float alpha = (255 * scale);
                    layoutTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                } else {    //滑动到banner下面设置普通颜色
                    layoutTitle.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                    titleBar.setTitle("合家云生活");
                }
            }
        });
        beanList = new ArrayList<>();
        listAdapter = new HomeGoodsListAdapter(beanList);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 3));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int i = parent.getChildLayoutPosition(view) % 3;//每行2个
                switch (i) {
                    case 0://第一个
                        outRect.left = (int) Dp2Px.dp2Px(9);
                        outRect.right = (int) Dp2Px.dp2Px(9);
                        break;
                    case 1://第二个
                        outRect.left = (int) Dp2Px.dp2Px(9);
                        outRect.right = (int) Dp2Px.dp2Px(9);
                        break;
                    case 3://第二个
                        outRect.left = (int) Dp2Px.dp2Px(9);
                        outRect.right = (int) Dp2Px.dp2Px(9);
                        break;
                }
            }
        });
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener(position -> {
            Intent intent = new Intent(mActivity, ShopGoodsDetailsActivity.class);
            intent.putExtra("goods_id", beanList.get(position).getId() + "");
            startActivity(intent);
        });

        menuBeanList = new ArrayList<>();
        menuListAdapter = new HomeMenuListAdapter(menuBeanList);
        recyclerViewMenu.setNestedScrollingEnabled(false);
        recyclerViewMenu.setLayoutManager(new GridLayoutManager(mActivity, 4));
        recyclerViewMenu.setAdapter(menuListAdapter);
        menuListAdapter.setOnCallBackListener(position -> {
            MenuListBean.DataBean dataBean = menuBeanList.get(position);
            if ("HousesRepair".equals(dataBean.getPath())) {
                skipToActivity(RepairsServiceActivity.class);
            }
            if ("Advisory".equals(dataBean.getPath())) {
                skipToActivity(ConsultServiceActivity.class);
            }
            if ("Housekeeping".equals(dataBean.getPath())) {
                skipToActivity(CleanServiceActivity.class);
            }
            if ("PropertyCosts".equals(dataBean.getPath())) {
                skipToActivity(PayFeeActivity.class);
            }
        });

    }

    public void requestAdIndex() {
        homePageModel.requestAdIndex(new DataCallBack<BannerListBean>() {
            @Override
            public void onSuccessful(BannerListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    xbanner.setVisibility(View.VISIBLE);
                    xbanner.setPageTransformer(Transformer.Default);
                    xbanner.setData(R.layout.item_banner_conner_iv, bean.getData().getItemList(), null);
                    xbanner.loadImage(new XBanner.XBannerAdapter() {
                        @Override
                        public void loadBanner(XBanner banner, Object model, View view, int position) {
                            ImageView view1 = (ImageView) view;
                            GlideUtils.loadImage(mActivity, view1, bean.getData().getItemList().get(position).getPic());
                            BannerListBean.DataBean.ItemListBean listBean = bean.getData().getItemList().get(position);
                            view.setOnClickListener(view2 -> {
                                if (listBean.getPath().contains("||")) {
                                    String[] str = listBean.getPath().split("\\|\\|");
                                    if ("ShopGoodsClass".equals(str[0])) {
                                        Intent intent = new Intent(mActivity, GoodsListActivity.class);
                                        intent.putExtra("query_str", str[1]);
                                        startActivity(intent);
                                    }
                                    if ("ShopGoods".equals(str[0])) {
                                        Intent intent = new Intent(mActivity, ShopGoodsDetailsActivity.class);
                                        intent.putExtra("query_str", str[1]);
                                        intent.putExtra("goods_id", "");
                                        startActivity(intent);
                                    }
                                    if ("Article".equals(str[0])) {
                                        Intent intent = new Intent(mActivity, UserAgreementActivity.class);
                                        intent.putExtra("type", 5);
                                        intent.putExtra("url", str[1]);
                                        startActivity(intent);
                                    }
                                } else {
                                    if ("ShopGoodsClass".equals(listBean.getPath())) {
                                        Intent intent = new Intent(mActivity, GoodsListActivity.class);
                                        intent.putExtra("query_str", "");
                                        startActivity(intent);
                                    }
                                    if ("ShopGoods".equals(listBean.getPath())) {
                                        Intent intent = new Intent(mActivity, ShopGoodsDetailsActivity.class);
                                        intent.putExtra("query_str", "");
                                        intent.putExtra("goods_id", "");
                                        startActivity(intent);
                                    }
                                    if ("HousesRepair".equals(listBean.getPath())) {
                                        skipToActivity(RepairsServiceActivity.class);
                                    }
                                    if ("Advisory".equals(listBean.getPath())) {
                                        skipToActivity(ConsultServiceActivity.class);
                                    }
                                    if ("Housekeeping".equals(listBean.getPath())) {
                                        skipToActivity(CleanServiceActivity.class);
                                    }
                                    if ("PropertyCosts".equals(listBean.getPath())) {
                                        skipToActivity(PayFeeActivity.class);
                                    }
                                }
                            });
                        }
                    });

                } else {
                    xbanner.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 商品列表
     */
    public void requestShopGoodsIndex() {
        homePageModel.requestShopGoodsIndex(1, 1, "", new DataCallBack<GoodsListBean>() {
            @Override
            public void onSuccessful(GoodsListBean bean) {
                beanList.clear();
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                }
                listAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAppMenu() {
        homePageModel.requestAppMenu("1", new DataCallBack<MenuListBean>() {
            @Override
            public void onSuccessful(MenuListBean bean) {
                menuBeanList.clear();
                if (bean.getData() != null && bean.getData().size() > 0) {
                    menuBeanList.addAll(bean.getData());
                }
                menuListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestMessageData() {
        homePageModel.requestIndexSystemMessage(1, new DataCallBack<IndexMessageBean>() {
            @Override
            public void onSuccessful(IndexMessageBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    llServiceRemind.setVisibility(View.VISIBLE);
                    if (bean.getData().getItemList().size() >= 2) {
                        llMessage1.setVisibility(View.VISIBLE);
                        llMessage2.setVisibility(View.VISIBLE);
                        IndexMessageBean.DataBean.ItemListBean data1 = bean.getData().getItemList().get(0);
                        tvMessage1.setText(data1.getContent());
                        tvMessageTime1.setText(DateTimeUtil.getTimeFormatText(new Date(Long.parseLong(data1.getCreate_time()) * 1000)));

                        IndexMessageBean.DataBean.ItemListBean data2 = bean.getData().getItemList().get(1);
                        tvMessage2.setText(data2.getContent());
                        tvMessageTime2.setText(DateTimeUtil.getTimeFormatText(new Date(Long.parseLong(data2.getCreate_time()) * 1000)));
                    } else {
                        llMessage1.setVisibility(View.VISIBLE);
                        llMessage2.setVisibility(View.GONE);
                        IndexMessageBean.DataBean.ItemListBean data1 = bean.getData().getItemList().get(0);
                        tvMessage1.setText(data1.getContent());
                        tvMessageTime1.setText(DateTimeUtil.getTimeFormatText(new Date(Long.parseLong(data1.getCreate_time()) * 1000)));
                    }
                } else {
                    llServiceRemind.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.ll_repairs, R.id.ll_consult, R.id.ll_clean, R.id.ll_fees, R.id.ll_service_remind, R.id.tv_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_repairs:
                skipToActivity(RepairsServiceActivity.class);
                break;
            case R.id.ll_consult:
                skipToActivity(ConsultServiceActivity.class);
                break;
            case R.id.ll_clean:
                skipToActivity(CleanServiceActivity.class);
                break;
            case R.id.ll_fees:
                skipToActivity(PayFeeActivity.class);
                break;
            case R.id.ll_service_remind:
                skipToActivity(ServiceRemindActivity.class);
                break;
            case R.id.tv_more:
                skipToActivity(GoodsListActivity.class);
                break;
        }
    }

}
